<template>
  <div class="template-list">
    <div class="header">
      <h2>简历模板</h2>
      <p class="subtitle">选择您喜欢的专业模板</p>
    </div>

    <div class="filters">
      <el-tabs v-model="activeCategory" @tab-change="filterTemplates">
        <el-tab-pane label="全部" name="all" />
        <el-tab-pane label="通用模板" name="general" />
        <el-tab-pane label="技术类" name="tech" />
        <el-tab-pane label="设计类" name="design" />
        <el-tab-pane label="学术类" name="academic" />
      </el-tabs>
    </div>

    <div class="template-grid">
      <el-row :gutter="20">
        <el-col :span="6" v-for="template in filteredTemplates" :key="template.id">
          <el-card class="template-card" @click="useTemplate(template)">
            <div class="template-preview">
              <img v-if="template.previewImage" :src="template.previewImage" :alt="template.name" />
              <div v-else class="placeholder-preview">
                <div class="template-icon">
                  <el-icon size="48" color="#409EFF"><Document /></el-icon>
                </div>
                <div class="template-type">{{ getCategoryName(template.category) }}模板</div>
              </div>
            </div>
            <div class="template-info">
              <h3>{{ template.name }}</h3>
              <p>{{ template.description }}</p>
              <div class="template-meta">
                <el-tag size="small" :type="getCategoryType(template.category)">
                  {{ getCategoryName(template.category) }}
                </el-tag>
                <span class="usage-count">{{ template.usageCount || 0 }} 次使用</span>
              </div>
            </div>
            <div class="template-actions">
              <el-button type="primary" size="small" @click.stop="useTemplate(template)">
                使用模板
              </el-button>
              <el-button size="small" @click.stop="previewTemplate(template)">
                预览
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div v-if="filteredTemplates.length === 0" class="empty-state">
      <el-icon size="100" color="#ddd"><Document /></el-icon>
      <h3>暂无模板</h3>
      <p>该分类下暂无可用模板</p>
    </div>

    <!-- 模板预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="模板预览"
      width="80%"
      center
    >
      <div class="preview-content" v-if="selectedTemplate">
        <div class="preview-header">
          <h3>{{ selectedTemplate.name }}</h3>
          <p>{{ selectedTemplate.description }}</p>
        </div>
        <div class="preview-image">
          <img v-if="selectedTemplate.previewImage" :src="selectedTemplate.previewImage" :alt="selectedTemplate.name" />
          <div v-else class="large-placeholder">
            <el-icon size="120" color="#ddd"><Document /></el-icon>
            <p>预览图片加载中...</p>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewVisible = false">取消</el-button>
          <el-button type="primary" @click="useSelectedTemplate">使用此模板</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getTemplateList } from '@/api/template'

const router = useRouter()

const activeCategory = ref('all')
const previewVisible = ref(false)
const selectedTemplate = ref(null)
const loading = ref(false)

const templates = ref([])

const filteredTemplates = computed(() => {
  if (activeCategory.value === 'all') {
    return templates.value
  }
  return templates.value.filter(template => template.category === activeCategory.value)
})

const filterTemplates = (category) => {
  activeCategory.value = category
}

const getCategoryName = (category) => {
  const categories = {
    general: '通用',
    tech: '技术',
    design: '设计',
    academic: '学术'
  }
  return categories[category] || category
}

const getCategoryType = (category) => {
  const types = {
    general: 'primary',
    tech: 'success',
    design: 'warning',
    academic: 'info'
  }
  return types[category] || 'primary'
}

const useTemplate = (template) => {
  ElMessage.success(`正在使用模板：${template.name}`)
  router.push({
    path: '/resumes/create',
    query: { templateId: template.id }
  })
}

const previewTemplate = (template) => {
  selectedTemplate.value = template
  previewVisible.value = true
}

const useSelectedTemplate = () => {
  if (selectedTemplate.value) {
    useTemplate(selectedTemplate.value)
    previewVisible.value = false
  }
}

const loadTemplates = async () => {
  try {
    loading.value = true
    
    try {
      // 优先从后端API加载
      const response = await getTemplateList()
      templates.value = response.data?.list || response.list || response || []
      console.log('从后端API加载模板，共', templates.value.length, '个')
    } catch (apiError) {
      console.error('后端API加载失败，使用默认模板:', apiError)
      
      // API失败时使用默认模板数据（不依赖图片）
      templates.value = [
        {
          id: 1,
          name: '经典专业模板',
          description: '适合大多数行业的经典设计，布局清晰，内容结构化',
          category: 'general',
          previewImage: null, // 暂时不使用图片
          usageCount: 156
        },
        {
          id: 2,
          name: '现代简约模板',
          description: '简洁现代的设计风格，突出重点信息',
          category: 'tech',
          previewImage: null,
          usageCount: 243
        },
        {
          id: 3,
          name: '创意设计模板',
          description: '适合设计师和创意工作者，版式灵活美观',
          category: 'design',
          previewImage: null,
          usageCount: 89
        },
        {
          id: 4,
          name: '学术研究模板',
          description: '适合学术和科研人员，突出教育和研究成果',
          category: 'academic',
          previewImage: null,
          usageCount: 67
        },
        {
          id: 5,
          name: '技术极客模板',
          description: '专为程序员设计的模板，突出技术技能',
          category: 'tech',
          previewImage: null,
          usageCount: 198
        },
        {
          id: 6,
          name: '商务精英模板',
          description: '适合管理层和商务人士，正式专业',
          category: 'general',
          previewImage: null,
          usageCount: 134
        },
        {
          id: 7,
          name: '艺术创作模板',
          description: '适合艺术家和自由职业者，展现个性',
          category: 'design',
          previewImage: null,
          usageCount: 76
        },
        {
          id: 8,
          name: '医学专业模板',
          description: '适合医护和生物科学专业，突出专业背景',
          category: 'academic',
          previewImage: null,
          usageCount: 45
        }
      ]
      console.log('使用默认模板数据，共', templates.value.length, '个')
    }
  } catch (error) {
    console.error('加载模板列表失败:', error)
    ElMessage.error('加载模板列表失败')
    templates.value = []
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadTemplates()
})
</script>

<style scoped>
.template-list {
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h2 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 28px;
}

.subtitle {
  color: #666;
  font-size: 16px;
  margin: 0;
}

.filters {
  margin-bottom: 30px;
}

.template-grid {
  margin-bottom: 30px;
}

.template-card {
  cursor: pointer;
  transition: transform 0.3s, box-shadow 0.3s;
  margin-bottom: 20px;
  height: 400px;
  display: flex;
  flex-direction: column;
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.template-preview {
  height: 200px;
  overflow: hidden;
  border-radius: 6px;
  margin-bottom: 15px;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.template-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.placeholder-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border: 2px dashed #409EFF;
}

.template-icon {
  margin-bottom: 10px;
}

.template-type {
  color: #409EFF;
  font-size: 14px;
  font-weight: 500;
}

.template-info {
  flex: 1;
  padding: 0 0 15px 0;
}

.template-info h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.template-info p {
  color: #666;
  margin: 0 0 12px 0;
  font-size: 14px;
  line-height: 1.4;
}

.template-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.usage-count {
  font-size: 12px;
  color: #999;
}

.template-actions {
  display: flex;
  gap: 10px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.template-actions .el-button {
  flex: 1;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-state h3 {
  margin: 20px 0 10px 0;
}

.empty-state p {
  margin: 0;
}

.preview-content {
  text-align: center;
}

.preview-header {
  margin-bottom: 20px;
}

.preview-header h3 {
  margin: 0 0 8px 0;
  color: #333;
}

.preview-header p {
  margin: 0;
  color: #666;
}

.preview-image {
  max-height: 600px;
  overflow: hidden;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.preview-image img {
  width: 100%;
  height: auto;
}

.large-placeholder {
  padding: 60px 20px;
  color: #ccc;
}

.large-placeholder p {
  margin: 20px 0 0 0;
  font-size: 16px;
}

.dialog-footer {
  text-align: right;
}
</style> 